package com.ibest.card.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ibest.framework.common.enums.EnumsRtnMapResult;
import com.ibest.framework.common.persistence.BaseController;
import com.ibest.framework.common.utils.PageList;
import com.ibest.framework.common.utils.UserUtils;
import com.ibest.integral.dto.input.UserIntegralCountInputDTO;
import com.ibest.integral.entity.Integral;
import com.ibest.integral.entity.IntegralCategory;
import com.ibest.integral.entity.UserIntegral;
import com.ibest.integral.entity.UserIntegralCount;
import com.ibest.user.entity.UserCars;
import com.ibest.user.service.UserCarsService;
import com.ibest.utils.ConstantUtils;
import com.ibest.utils.RandomUtils;
import com.ibest.accesssystem.entity.AccessSystem;
import com.ibest.accesssystem.service.AccessSystemService;
import com.ibest.activity.entity.ActivityIntegral;
import com.ibest.card.dto.input.CardOperationInputDTO;
import com.ibest.card.dto.input.UserCardCountInputDTO;
import com.ibest.card.entity.CardOperation;
import com.ibest.card.entity.UserCard;
import com.ibest.card.entity.UserCardCount;
import com.ibest.card.service.CardOperationService;
import com.ibest.card.service.UserCardCountService;
import com.ibest.card.service.UserCardService;

@Controller
@RequestMapping(value="${adminPath}/card/cardOperation")
public class CardOperationController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(CardOperationController.class);
	
	@Autowired
	private CardOperationService cardOperationService;
	
	@Autowired
	private UserCarsService carsService;
	
	@Autowired
	private UserCardService userCardService;
	
	@Autowired
	private UserCardCountService userCardCountService;
	
	@Autowired
	private AccessSystemService access;
	
	/**
	* 进入到列表页
	*/
	@RequestMapping(value="/")
	public String index(){
		return "module/card/cardOperation/cardOperationList";
	}
	
	/**
	* 进入到表单页-创建
	*/
	@RequestMapping(value="/add")
	public String add(){
		
		return "module/card/cardOperation/cardOperationForm";
	}
	
	/**
	* 进入到表单页，编辑
	*/
	@RequestMapping(value="/edit")
	public String edit(@RequestParam String id, Model model){
		try {
			if(StringUtils.isNotEmpty(id)){
				CardOperation cardOperation = cardOperationService.findById(id);
				if(cardOperation != null){
					model.addAttribute("cardOperation", cardOperation);
				}else{
					setRtnCodeAndMsg(EnumsRtnMapResult.FAILURE.getCode(), "您查看的信息不存在！", model);
				}
			}else{
				setRtnCodeAndMsg(EnumsRtnMapResult.FAILURE.getCode(), "请选择需要编辑的信息！", model);
			}
		} catch (Exception e) {
			setRtnCodeAndMsg(EnumsRtnMapResult.EXCEPTION.getCode(), EnumsRtnMapResult.EXCEPTION.getMsg(), model);
		}
		return "module/card/cardOperation/cardOperationForm";
	}
	
	/**
	* 进入到详情页
	*/
	@RequestMapping(value="/view")
	public String view(@RequestParam String id, Model model){
		try {
			if(StringUtils.isNotEmpty(id)){
				CardOperation cardOperation = cardOperationService.findById(id);
				if(cardOperation != null){
					model.addAttribute("cardOperation", cardOperation);
				}else{
					setRtnCodeAndMsg(EnumsRtnMapResult.FAILURE.getCode(), "您查看的信息不存在！", model);
				}
			}else{
				setRtnCodeAndMsg(EnumsRtnMapResult.FAILURE.getCode(), "请选择需要查看的信息！", model);
			}
		} catch (Exception e) {
			setRtnCodeAndMsg(EnumsRtnMapResult.EXCEPTION.getCode(), EnumsRtnMapResult.EXCEPTION.getMsg(), model);
		}
		return "module/card/cardOperation/cardOperationDetail";
	}

	/**
	* 异步分页查询
	*/
	@ResponseBody
	@RequiresPermissions("cardOperation:query")
	@RequestMapping(value="/list")
	public PageList<CardOperation> list(CardOperationInputDTO cardOperation, HttpServletRequest request){
		
		PageList<CardOperation> pageList = new PageList<CardOperation>();
		
		try {
			//设置分页参数
			super.setPage(request, pageList);
		
			pageList = cardOperationService.findByPage(pageList, cardOperation);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pageList;
	}
	
	/**
	* 异步表单提交
	*/
	@ResponseBody
	@RequiresPermissions("cardOperation:create")
	@RequestMapping(value="create")
	public Map<String, Object> insert(CardOperation cardOperation){

		Map<String, Object> rtnMap = new HashMap<String, Object>();
		setRtnCodeAndMsgBySuccess(rtnMap, "保存成功");
		
		try {
			cardOperation.setSystemId(cardOperation.getSystemId().replace(",",""));
			cardOperation.setUserId(cardOperation.getUserId().replace(",",""));
			cardOperation.setIsDelete(ConstantUtils.UPDATE_SET_ZERO);
			cardOperation.setCarId(cardOperation.getCarId().replace(",",""));
			cardOperation.setId(RandomUtils.RandomUUID());
			cardOperation.setGrantOrRecall("0");
			cardOperation.setCreater(UserUtils.getCurrentUser().getRealname());
			cardOperation.setCreateTime(new Date());
			cardOperation.setModifier(UserUtils.getCurrentUser().getRealname());
			cardOperation.setModifyTime(new Date());
			int result = cardOperationService.insert(cardOperation);
			if(result == 0){
				setRtnCodeAndMsgByFailure(rtnMap, "保存失败");
			}
			String carId =cardOperation.getCarId();
			UserCars findById = carsService.findById(carId);
			String vinNo ="";
			if(findById!=null){
				 vinNo=findById.getVinCode();
			}
			AccessSystem accessSystem = access.findById(cardOperation.getSystemId());
			String accessName =accessSystem.getIdentification();
			//发放的数量
			Integer num=Integer.parseInt(cardOperation.getGrantNum());
			for(int i=0;i<num;i++){
				UserCard userCard=new UserCard();
				userCard.setId(RandomUtils.RandomUUID());
				userCard.setAccessSystemId(accessName);
				userCard.setAppId("05");
				userCard.setDealerId(cardOperation.getDealerId());
				userCard.setUserId(cardOperation.getUserId());
				userCard.setVinNo(vinNo);
				userCard.setCardId(cardOperation.getCardId());
				userCard.setCardNo(RandomUtils.getCardNo());
				userCard.setState("0");
				userCard.setCreateTime(new Date());
				userCard.setModifyTime(new Date());	
				int insert = userCardService.insert(userCard);
				if(insert == 0){
					setRtnCodeAndMsgByFailure(rtnMap, "操作失败");
				}
			}
			
			UserCardCountInputDTO userCardCountInputDTO=new UserCardCountInputDTO();
			userCardCountInputDTO.setAccessSystemId(accessName);
			userCardCountInputDTO.setAppId("05");
			userCardCountInputDTO.setUserId(cardOperation.getUserId());
			userCardCountInputDTO.setVinNo(vinNo);
			userCardCountInputDTO.setCardId(cardOperation.getCardId());
			
			UserCardCount userCardCount=userCardCountService.findOneByObject(userCardCountInputDTO);
			if(userCardCount !=null) {
				int number=userCardCount.getNumber()+num;
				userCardCount.setNumber(number);
				userCardCount.setModifyTime(new Date());
				int update = userCardCountService.update(userCardCount);
				if(update == 0){
					setRtnCodeAndMsgByFailure(rtnMap, "操作失败");
				}
			}else {
				UserCardCount userCardCount2=new UserCardCount();
				userCardCount2.setId(RandomUtils.RandomUUID());
				userCardCount2.setAccessSystemId(accessName);
				userCardCount2.setAppId("05");
				userCardCount2.setUserId(cardOperation.getUserId());
				userCardCount2.setVinNo(vinNo);
				userCardCount2.setCardId(cardOperation.getCardId());
				userCardCount2.setNumber(num);
				userCardCount2.setCreateTime(new Date());
				userCardCount2.setModifyTime(new Date());
				int insert = userCardCountService.insert(userCardCount2);
				if(insert == 0){
					setRtnCodeAndMsgByFailure(rtnMap, "操作失败");
				}
				
			}		
		} catch (Exception e) {
			e.printStackTrace();
			setRtnCodeAndMsgByException(rtnMap, null);
		}
		return rtnMap;
	}
	
	@ResponseBody
	@RequiresPermissions("cardOperation:update")
	@RequestMapping(value="update")
	public Map<String, Object> update(CardOperation cardOperation){

		Map<String, Object> rtnMap = new HashMap<String, Object>();
		setRtnCodeAndMsgBySuccess(rtnMap, "保存成功");
		
		try {
			cardOperation.setModifier(UserUtils.getCurrentUser().getRealname());
			cardOperation.setModifyTime(new Date());
			int result = cardOperationService.update(cardOperation);
			if(result == 0){
				setRtnCodeAndMsgByFailure(rtnMap, "保存失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			setRtnCodeAndMsgByException(rtnMap, null);
		}
		return rtnMap;
	}
	
	@ResponseBody
	@RequiresPermissions("cardOperation:delete")
	@RequestMapping(value="delete")
	public Map<String, Object> delete(@RequestParam(required=true) String ids){
		
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		setRtnCodeAndMsgBySuccess(rtnMap, "删除成功");
		
		try {
			int result = cardOperationService.deleteByIds(ids);
			if(result == 0){
				setRtnCodeAndMsgByFailure(rtnMap, "删除失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			setRtnCodeAndMsgByException(rtnMap, null);
		}
		return rtnMap;
	}
}
